package com.gexiaobao.pigeon.ui.fragment.match

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.util.ImgUtils
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.WxShareUtils
import com.gexiaobao.pigeon.databinding.FragmentCarVehicleRouteBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.dialog.RxDialogScreenShot
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 11:00
 * @Describe    : 车辆路线
 */
class FragmentCarVehicleRoute : BaseFragment<RaceViewModel, FragmentCarVehicleRouteBinding>() {

    private var bitmap: Bitmap? = null
    private var mId = ""
    private var webViewHeaderValue = ""

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mId = arguments?.getInt("id").toString()
        val title = arguments?.getString("title")
        title?.let {
            mDatabind.toolbar.initClose(it) {
                nav().navigateUp()
            }
        }

        initWebView()
    }

    @SuppressLint("JavascriptInterface")
    private fun initWebView() {
        webViewHeaderValue = KvUtils.decodeString(Constant.TOKEN)
        val webUrl = Constant.CAR_VEHICLE_ROUTE_URL + "/r/v1/pass/carMap/$mId"//正式
        LogUtils.debugInfo(webUrl)
        val map = mapOf("x-token" to webViewHeaderValue)
        mDatabind.webView.loadUrl(webUrl, map)
        val webSettings = mDatabind.webView.settings
        webSettings.userAgentString = webSettings.userAgentString + "Android-Pigeon"
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.javaScriptEnabled = true//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.setSupportZoom(true)//是否可以缩放，默认true
        webSettings.builtInZoomControls = false//是否显示缩放按钮，默认false
        webSettings.useWideViewPort = true//设置此属性，可任意比例缩放。大视图模式
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式

        mDatabind.webView.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        mDatabind.webView.webChromeClient = webChromeClient
        mDatabind.webView.webViewClient = webViewClient
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {//页面加载完成
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            return super.shouldOverrideUrlLoading(view, url)
        }
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (mDatabind.progressBar != null) {
                mDatabind.progressBar.visibility = View.VISIBLE
                mDatabind.progressBar.progress = newProgress
                if (newProgress == 100) {
                    mDatabind.progressBar.visibility = View.GONE
                }
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvShare, mDatabind.tvRefreshMap) {
            when (it) {
                mDatabind.tvShare -> {
                    requestPermission()
                }

                mDatabind.tvRefreshMap -> {
                    mDatabind.webView.reload()
                }
            }
        }
    }

    private fun requestPermission() {
        mDatabind.tvShare.postDelayed({
            XXPermissions.with(this)
                // 适配分区存储应该这样写
                .permission(Permission.READ_MEDIA_IMAGES)
                .interceptor(PermissionInterceptor())
                .request(OnPermissionCallback { _, allGranted ->
                    if (!allGranted) {
                        RxToast.showToast(getString(R.string.permission_acquisition_failure))
                        return@OnPermissionCallback
                    }
                    bitmap = ImgUtils.takeScreenShot(activity, mDatabind.toolbar)
                    val url = ImgUtils.getRealFilePath(context, ImgUtils.saveAlbum(activity, bitmap, Bitmap.CompressFormat.JPEG, 80, false))
                    showScreenShotDialog(bitmap, url)
                })
        }, 1000)
    }

    private fun showScreenShotDialog(bitmap: Bitmap?, path: String) {
        val dialog = RxDialogScreenShot(context)
        bitmap?.let { dialog.setScreenShotImage(it) }
        dialog.setSureListener {
            dialog.dismiss()
            WxShareUtils.sharePicture(
                context, Constant.WX_APP_ID,
                path
            )
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun onDestroyView() {
        if (mDatabind.webView != null) {
            mDatabind.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            mDatabind.webView.clearHistory()
            mDatabind.webView.destroy()
        }
        bitmap?.recycle()
        super.onDestroyView()
    }
}